#!/bin/bash
# 网络服务监控脚本

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${SCRIPT_DIR}/../config.yaml"

# 检查服务状态
check_service() {
    local service=$1
    if systemctl is-active --quiet "$service"; then
        echo "✓ $service: 运行中"
        return 0
    else
        echo "✗ $service: 未运行"
        return 1
    fi
}

# 检查服务详细状态
check_service_detail() {
    local service=$1
    echo ""
    echo "--- $service 详细状态 ---"
    systemctl status "$service" --no-pager -l | head -10
}

# 检查网络接口
check_interface() {
    local iface=$1
    if ip link show "$iface" &>/dev/null; then
        local state=$(ip link show "$iface" 2>/dev/null | grep -oP '(?<=state )[A-Z]+' || echo "UNKNOWN")
        local ip=$(ip addr show "$iface" 2>/dev/null | grep -oP '(?<=inet )[\d.]+' | head -1)
        local master=$(ip link show "$iface" 2>/dev/null | grep -oP '(?<=master )[^\s]+' || echo "")
        
        local status_line="✓ $iface: $state"
        if [ -n "$ip" ]; then
            status_line="$status_line, IP: $ip"
        fi
        if [ -n "$master" ]; then
            status_line="$status_line, master: $master"
        fi
        echo "$status_line"
        return 0
    else
        echo "✗ $iface: 不存在"
        return 1
    fi
}

# 从配置文件读取接口名称（如果存在）
get_config_value() {
    local key=$1
    if [ -f "$CONFIG_FILE" ]; then
        grep -E "^\s*${key}:" "$CONFIG_FILE" | sed 's/.*:\s*//' | sed 's/#.*//' | tr -d ' ' | head -1
    fi
}

# 检测无线网卡（支持 wlp、wlan、wlx 开头）
detect_wireless_interfaces() {
    ip -br link show | grep -E '^(wlp|wlan|wlx)' | awk '{print $1}'
}

# 检测有线网卡（排除无线和虚拟接口）
detect_ethernet_interfaces() {
    ip -br link show | grep -vE '^(lo|docker|veth|br-|wlp|wlan|wlx)' | grep -E '^(enp|eth|ens)' | awk '{print $1}'
}

echo "=========================================="
echo "Ubuntu 路由器服务状态监控"
echo "=========================================="
echo ""

# 网络服务状态
echo "网络服务状态:"
check_service "dnsmasq"
check_service "hostapd"
check_service "create-ap-interface"
check_service "avahi-daemon"
echo ""

# 从配置文件读取 WAN 口（如果配置文件存在）
WAN_INTERFACE=""
if [ -f "$CONFIG_FILE" ]; then
    # 尝试从 wan.interface 读取
    WAN_INTERFACE=$(grep -A 5 "^wan:" "$CONFIG_FILE" | grep "interface:" | sed 's/.*interface:\s*//' | sed 's/#.*//' | tr -d ' ' | head -1)
fi

# 从配置文件读取无线 AP 接口
WIRELESS_AP_INTERFACE=""
if [ -f "$CONFIG_FILE" ]; then
    # 尝试从 wireless_ap.interface 读取物理接口
    WIRELESS_AP_PHYSICAL=$(grep -A 10 "^wireless_ap:" "$CONFIG_FILE" | grep "interface:" | sed 's/.*interface:\s*//' | sed 's/#.*//' | tr -d ' ' | head -1)
    if [ -n "$WIRELESS_AP_PHYSICAL" ]; then
        # 虚拟接口命名规则：物理接口名 + ap
        WIRELESS_AP_INTERFACE="${WIRELESS_AP_PHYSICAL}ap"
    fi
fi

# 从配置文件读取 LAN 接口列表
LAN_INTERFACES=()
if [ -f "$CONFIG_FILE" ]; then
    # 读取 LAN 接口列表
    while IFS= read -r line; do
        # 提取 YAML 列表中的接口名称（处理 - enp3s0 格式）
        iface=$(echo "$line" | sed 's/.*-\s*//' | sed 's/#.*//' | tr -d ' ')
        if [ -n "$iface" ] && [[ "$iface" =~ ^(enp|eth|ens) ]]; then
            LAN_INTERFACES+=("$iface")
        fi
    done < <(grep -A 10 "^lan:" "$CONFIG_FILE" | grep -E "^\s*-")
fi

# 网络接口状态
echo "网络接口状态:"
echo "--- WAN 口 ---"
if [ -n "$WAN_INTERFACE" ]; then
    check_interface "$WAN_INTERFACE"
    echo "  (从配置文件读取: $WAN_INTERFACE)"
else
    echo "⚠ 无法从配置文件读取 WAN 口，尝试检测..."
    for iface in $(detect_ethernet_interfaces | head -1); do
        check_interface "$iface"
    done
fi

echo ""
echo "--- LAN 网桥 ---"
check_interface "br-lan"

echo ""
echo "--- LAN 口（网桥成员）---"
# 优先从配置文件读取，如果没有则检测网桥成员
if [ ${#LAN_INTERFACES[@]} -gt 0 ]; then
    echo "  (从配置文件读取: ${LAN_INTERFACES[*]})"
    for iface in "${LAN_INTERFACES[@]}"; do
        check_interface "$iface"
    done
else
    # 检测网桥成员
    if ip link show br-lan &>/dev/null; then
        bridge_ports=$(ip link show br-lan 2>/dev/null | grep -oP '(?<=master br-lan )[^\s]+' || echo "")
        if [ -z "$bridge_ports" ]; then
            bridge_ports=$(bridge link show 2>/dev/null | grep "br-lan" | awk '{print $2}' | cut -d: -f2)
        fi
        if [ -n "$bridge_ports" ]; then
            for port in $bridge_ports; do
                check_interface "$port"
            done
        else
            echo "⚠ 无法检测网桥成员"
        fi
    else
        echo "⚠ br-lan 网桥不存在"
    fi
fi

echo ""
echo "--- 无线接口 ---"
# 优先检查配置文件中指定的接口
if [ -n "$WIRELESS_AP_INTERFACE" ]; then
    # 检查物理接口
    if [ -n "$WIRELESS_AP_PHYSICAL" ]; then
        check_interface "$WIRELESS_AP_PHYSICAL"
        echo "  (物理接口，从配置文件读取)"
    fi
    # 检查虚拟 AP 接口
    check_interface "$WIRELESS_AP_INTERFACE"
    echo "  (虚拟AP接口，从配置文件读取)"
else
    # 如果没有配置文件，则自动检测
    for iface in $(detect_wireless_interfaces); do
        check_interface "$iface"
        # 检查对应的虚拟接口
        ap_iface="${iface}ap"
        if ip link show "$ap_iface" &>/dev/null; then
            check_interface "$ap_iface"
        fi
    done
fi

echo ""
echo "--- IP 转发状态 ---"
if [ "$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null)" = "1" ]; then
    echo "✓ IP 转发已启用"
else
    echo "✗ IP 转发未启用"
fi

echo ""
echo "--- NAT 规则 ---"
if command -v iptables &>/dev/null; then
    iptables -t nat -L POSTROUTING -n --line-numbers 2>/dev/null || echo "无法查看 NAT 规则（可能需要 root 权限）"
else
    echo "⚠ iptables 未安装"
fi

echo ""
echo "--- hostapd 进程检查 ---"
if pgrep -f "hostapd" &>/dev/null; then
    hostapd_pids=$(pgrep -f "hostapd")
    echo "✓ hostapd 进程运行中 (PID: $hostapd_pids)"
    # 显示 hostapd 使用的接口
    for pid in $hostapd_pids; do
        if [ -f "/proc/$pid/cmdline" ]; then
            cmdline=$(cat /proc/$pid/cmdline 2>/dev/null | tr '\0' ' ')
            echo "  命令: $cmdline"
        fi
    done
else
    echo "✗ hostapd 进程未运行"
fi

echo ""
echo "=========================================="

